# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_recommender_session_id'
  
  before_filter :set_locale
  
  def set_locale  # if user clicked on a link for selecting his locale
    if !params[:locale].nil? && locale = params[:locale].match( ENV['APP_AVAILABLE_LOCALES'] )
 #     puts "locale specified in params"
      session[:locale] = locale[0]  
    # or if the locale is already set in the session
    elsif !session[:locale].nil? && session[:locale].match( ENV['APP_AVAILABLE_LOCALES'] )  
      # or if the browser sends its locale  
#      puts "we already have a locale in the session"
    elsif !request.env['HTTP_ACCEPT_LANGUAGE'].nil? && locale = request.env['HTTP_ACCEPT_LANGUAGE'].match(ENV['APP_AVAILABLE_LOCALES'] ) 
#      puts "browser sent locale"
      session[:locale] = locale[0]  # else we're not lucky  
    else 
#      puts "default locale"
      session[:locale] = ENV['APP_DEFAULT_LOCALE']  
    end
    Localization.use session[:locale]
  end
end
